//
//  HANetworkRequest.m
//  HAFund
//
//  Created by 夏成龙 on 2018/10/30.
//  Copyright © 2018年 夏成龙. All rights reserved.
//

#import "HARequest.h"
#import "FactoryClass.h"
#import "HANetworkConfig.h"

#import <AFNetworking.h>



@interface HARequest ()

@property (nonatomic, strong) AFHTTPSessionManager *sessionMgr;

@end

@implementation HARequest

+ (instancetype)instance {
    static HARequest *request = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        request = [[self alloc] init];
        [request setCommonGatewayHead];
    });
    return request;
}

- (AFHTTPRequestSerializer *)requestHead {
    if (!_requestHead) {
        _requestHead = [AFHTTPRequestSerializer serializer];
    }
    return _requestHead;
}


+ (instancetype)requestWithURLString:(NSString *)path params:(NSDictionary *)params type:(HARequestType)requestType {
    return [[self instance] initWithURLString:path params:params type:requestType];
}

- (instancetype)initWithURLString:(NSString *)path params:(NSDictionary *)params type:(HARequestType)requestType {
    if ([super init]) {
        NSString *methodStr;
        if (requestType == HARequestTypeGET) {
            methodStr = @"GET";
        } else if (requestType == HARequestTypePOST) {
            methodStr = @"POST";
        }
        
        // 设置请求头信息
         [self setGatewayTimeHead];
        HANetworkConfig *config = [HANetworkConfig instance];
        NSString *requestURL = [NSString stringWithFormat:@"%@/%@",config.baseURL, path];
        NSDictionary *requestParam = nil;
        if (requestType == HARequestTypeGET) {
           requestParam  = [self getEncryptParamFromParams:params];
        } else {
            requestParam = params;
        }

        _request = [self.requestHead requestWithMethod:methodStr URLString:requestURL parameters:requestParam error:NULL];
        if (requestType == HARequestTypePOST) {
            _request.HTTPBody = [self postEncryptParamFromParams:params];
        }
    }
    return self;
}

- (NSDictionary *)getEncryptParamFromParams:(NSDictionary *)params {
    NSDictionary *encryptParam = nil;
    if ([params isKindOfClass:[NSDictionary class]]) {
        NSMutableString *paramStr = [NSMutableString string];
        BOOL flag = NO;
        for (NSString *key in [(NSDictionary *)params allKeys]) {
            if (flag) {
                [paramStr appendString:@"&"];
            }
            flag = YES;
            [paramStr appendFormat:@"%@=%@", key, params[key]];
        }
        NSString *encryptParamStr = [FactoryClass getAesEncrypt: paramStr];
        encryptParam = @{@"data": encryptParamStr};
    }
    return encryptParam;
}

- (NSData *)postEncryptParamFromParams:(NSDictionary *)params {
    NSData *paramsData = nil;
    if ([params isKindOfClass:[NSDictionary class]]) {
        paramsData = [NSJSONSerialization dataWithJSONObject:params options:0 error:NULL];
    } else if([params isKindOfClass:[NSString class]]){
        paramsData = [(NSString *)params dataUsingEncoding:NSUTF8StringEncoding];
    } else if([params isKindOfClass:[NSData class]]){
        paramsData = (NSData *)params;
    }
    
    //加密body
    NSString *bodyStr =  [[NSString alloc] initWithData:paramsData encoding:NSUTF8StringEncoding];
    bodyStr = [FactoryClass getAesEncrypt:bodyStr];
    return [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
}

- (void)setCommonGatewayHead {
   /*
    [self.requestHead setValue:@"000000000000" forHTTPHeaderField:@"channelId"];
    //[self.httpRequestSerializer setValue:[BaseNetworkBL currentUserunDecodeUserId] forHTTPHeaderField:@"userId"];
    [self.requestHead setValue:@"APP" forHTTPHeaderField:@"tradeMode"];
    [self.requestHead setValue:@"1026" forHTTPHeaderField:@"senderId"];

    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    //#设备信息
    NSDictionary *deviceInfo= @{
                                @"osType":@"iOS",
                                @"osVersion":[[UIDevice currentDevice] systemVersion],
                                @"brand":[[UIDevice currentDevice] model],
                                @"appId":[UIDevice getUDID],
                                @"bbVersion":app_Version
                                };
    //格式化
    NSError *parseError = nil;
    NSData *deviceInfoData = [NSJSONSerialization dataWithJSONObject:deviceInfo options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *deviceInfoStr = [[NSString alloc] initWithData:deviceInfoData encoding:NSUTF8StringEncoding];
    deviceInfoStr = [deviceInfoStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    [self.requestHead setValue:deviceInfoStr forHTTPHeaderField:@"headPar"];
    */
    NSDictionary *headParam = [HANetworkConfig instance].commonHeadParams;
    for (NSString *key in headParam) {
        [self.requestHead setValue:headParam[key] forHTTPHeaderField:key];
    }
    [self.requestHead setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
}

/**设置每次网关请求报文头*/
- (void)setGatewayTimeHead {
    /*
    //#登录信息
    NSDate * date = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyyMMdd.HHmmssSSS";
    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    NSString * times = [dateFormatter stringFromDate:date];
    int radom = arc4random() % 1000000;
    //    NSDictionary *params =@{
    //                            @"times":times,
    //                            @"random": @(radom),
//    @"userId":mAvailableString([FactoryClassTool currentUser].userId),
//    @"cid":mAvailableString([JXUserDefault objectValueForKey:kCurrentUserUnunDecodeUserId]),
    //                            };
    NSString *userId = @"";
    NSString *cid = @"";
    NSString *paramsEncryptHead = [NSString stringWithFormat:@"{times=%@,random=%d,userId=%@,cid=%@}", times, radom, userId, cid];
    //格式化和加密/
    NSString *paramStr= [FactoryClass getAesEncrypt:paramsEncryptHead];
    [self.requestHead setValue:paramStr forHTTPHeaderField:@"auth"];
    
    dateFormatter.dateFormat = @"yyyyMMdd";
    NSString * dateStr = [dateFormatter stringFromDate:date];
    dateFormatter.dateFormat = @"HHmmss";
    NSString * timeStr = [dateFormatter stringFromDate:date];
    
    [self.requestHead setValue:dateStr forHTTPHeaderField:@"sysDate"];
    [self.requestHead setValue:timeStr forHTTPHeaderField:@"sysTime"];
    */
    NSDictionary *extraParam = [HANetworkConfig instance].extraHeadParams;
    for (NSString *key in extraParam) {
        [self.requestHead setValue:extraParam[key] forHTTPHeaderField:key];
    }
}


@end
